import db from './createDb'
import Mock from 'mockjs'
import md5 from 'md5'
import jwt from 'jsonwebtoken'

// 登录模块
Mock.mock('user/login', 'post', function (info) {
  const { userName, password } = JSON.parse(info.body)
  const stateResult = db.select('zy_users', item => item.userName === userName && item.state === 1)
  const result = db.select('zy_users', item => item.userName === userName && item.password === md5(password) && item.state === 2)
  if (stateResult && stateResult.length > 0) {
    return { err: 1003, desc: '你的账号还未审核通过' }
  }
  if (result && result.length > 0) {
    let token = ''
    try {
      // 登录成功颁发授权码  token expiresIn 过去时间 1h表示1小时后，30表示30秒
      token = jwt.sign({ data: userName }, '0401', { expiresIn: '1d' })
    } catch (err) {
      console.log(err)
    }
    return { err: 0, desc: '登录成功', token }
  } else {
    return { err: 1001, desc: '账号或密码错误' }
  }
})
